<template>
	<div class="role-select-container">
		<div class="role-select-card">
			<h2 class="title">选择角色</h2>
			<div class="role-list">
				<div v-if="roleList.length === 0" class="no-roles">
					<div class="no-roles-icon">👤</div>
					<div class="no-roles-text">暂无角色</div>
					<div class="no-roles-desc">您还没有创建角色，请先创建一个角色开始游戏</div>
				</div>
				<div 
					v-else
					v-for="role in roleList" 
					:key="role.id" 
					class="role-item"
					:class="{ active: selectedRoleId === role.id }"
					@click="selectRole(role)"
				>
					<div class="role-avatar">
						<img :src="role.avatar || '/static/default-avatar.svg'" :alt="role.name">
					</div>
					<div class="role-info">
						<div class="role-name">{{ role.name }}</div>
						<div class="role-level">等级: {{ role.level || 1 }}</div>
						<div class="role-district">区服: {{ role.district || 'default' }}</div>
					</div>
				</div>
			</div>
			
			<div class="action-buttons">
				<button 
					v-if="roleList.length > 0"
					class="btn btn-primary"
					:disabled="!selectedRoleId || enterLoading"
					@click="enterGame"
				>
					{{ enterLoading ? '进入中...' : '进入游戏' }}
				</button>
				<button 
					v-if="roleList.length === 0"
					class="btn btn-primary"
					@click="createRole"
				>
					创建角色
				</button>
				<button class="btn btn-secondary" @click="logout">退出登录</button>
			</div>
		</div>
		
		<!-- 创建角色模态框 -->
		<div v-if="showCreateModal" class="modal-overlay" @click="closeCreateModal">
			<div class="modal-content" @click.stop>
				<div class="modal-header">
					<h3>创建角色</h3>
					<button class="close-btn" @click="closeCreateModal">×</button>
				</div>
				<div class="modal-body">
					<div class="form-group">
						<label>角色昵称</label>
						<div class="nickname-input-group">
							<input 
								v-model="newRoleName" 
								type="text" 
								placeholder="请输入角色昵称" 
								maxlength="8"
								class="nickname-input"
							/>
							<button 
								class="random-btn" 
								@click="generateRandomNickname"
								title="随机生成昵称"
							>
								🎲
							</button>
						</div>
						<div class="nickname-hint">昵称长度为2-8个字符，支持中文、英文和数字</div>
					</div>
				</div>
				<div class="modal-footer">
					<button class="btn btn-secondary" @click="closeCreateModal">取消</button>
					<button 
						class="btn btn-primary" 
						:disabled="!newRoleName.trim() || createLoading"
						@click="confirmCreateRole"
					>
						{{ createLoading ? '创建中...' : '创建角色' }}
					</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import request from '../../src/api/request.js'
import nicknamesConfig from '../../src/config/nicknames.json'

export default {
	data() {
		return {
			roleList: [],
			selectedRoleId: null,
			enterLoading: false,
			showCreateModal: false,
			newRoleName: '',
			createLoading: false
		}
	},
	mounted() {
		// 从localStorage加载角色列表
		this.loadRoleList()
	},
	methods: {
		loadRoleList() {
			// 从localStorage获取角色列表
			const roleListStr = localStorage.getItem('role_list')
			if (roleListStr) {
				try {
					this.roleList = JSON.parse(roleListStr)
					if (this.roleList.length === 1) {
						// 如果只有一个角色，自动选中
						this.selectedRoleId = this.roleList[0].id || this.roleList[0].role_id
					}
				} catch (error) {
					console.error('解析角色列表失败:', error)
					this.roleList = []
				}
			}
			
			// 如果没有角色，显示创建角色选项
			if (this.roleList.length === 0) {
				console.warn('未找到角色信息，需要创建角色')
			}
		},
		
		selectRole(role) {
			this.selectedRoleId = role.id || role.role_id
		},
		
		enterGame() {
			if (!this.selectedRoleId) {
				alert('请选择一个角色')
				return
			}
			
			this.enterLoading = true
			
			// 保存选中的角色ID
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('role_id', this.selectedRoleId)
			} else {
				localStorage.setItem('role_id', this.selectedRoleId)
			}
			
			// 直接跳转到主页，由主页负责调用role/info接口
			// 使用 uni.navigateTo 确保兼容性
			if (typeof uni !== 'undefined' && uni.navigateTo) {
				uni.navigateTo({ url: '/pages/main/index' })
			} else {
				window.location.hash = '#/pages/main/index'
			}
		},
		
		createRole() {
			this.showCreateModal = true
			this.generateRandomNickname()
		},
		
		closeCreateModal() {
			this.showCreateModal = false
			this.newRoleName = ''
			this.createLoading = false
		},
		
		generateRandomNickname() {
			const nicknames = nicknamesConfig.nicknames
			const randomIndex = Math.floor(Math.random() * nicknames.length)
			this.newRoleName = nicknames[randomIndex]
		},
		
		async confirmCreateRole() {
			if (!this.newRoleName.trim()) {
				alert('请输入角色昵称')
				return
			}
			
			if (this.newRoleName.length < 2 || this.newRoleName.length > 8) {
				alert('昵称长度必须为2-8个字符')
				return
			}
			
			this.createLoading = true
			
			try {
				// 调用后端接口创建角色
				const response = await request.post('/role/register', {
					name: this.newRoleName.trim()
				})
				
				if (response && response.data) {
					// 创建成功，保存role_id
					const roleId = response.data.role_id || response.data.id
					if (roleId) {
						(typeof uni !== 'undefined' ? uni.setStorageSync('role_id', roleId) : localStorage.setItem('role_id', roleId))
					}
					
					// 关闭模态框
					this.closeCreateModal()
					
					// 直接跳转到主页，由主页负责调用role/info接口
					window.location.hash = '/pages/main/index'
				} else {
					alert('创建角色失败，请重试')
				}
			} catch (error) {
				console.error('创建角色失败:', error)
				alert(error.message || '创建角色失败，请重试')
			} finally {
				this.createLoading = false
			}
		},
		

		
		/**
		 * 清理localStorage，只保留yid和role_id
		 */
		cleanupLocalStorage() {
			// 获取需要保留的值
			const yid = (typeof uni !== 'undefined' ? uni.getStorageSync('yid') : localStorage.getItem('yid'))
			const roleId = (typeof uni !== 'undefined' ? uni.getStorageSync('role_id') : localStorage.getItem('role_id'))
			
			// 清除所有localStorage
			localStorage.clear()
			
			// 重新设置需要保留的值
			if (yid) {
				(typeof uni !== 'undefined' ? uni.setStorageSync('yid', yid) : localStorage.setItem('yid', yid))
			}
			if (roleId) {
				(typeof uni !== 'undefined' ? uni.setStorageSync('role_id', roleId) : localStorage.setItem('role_id', roleId))
			}
		},
		
		logout() {
			// 只清除yid和role_id
			if (typeof uni !== 'undefined') {
				uni.removeStorageSync('yid')
				uni.removeStorageSync('role_id')
			} else {
				localStorage.removeItem('yid')
				localStorage.removeItem('role_id')
			}
		}
	}
}
</script>

<style scoped>
.role-select-container {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 20px;
}

.role-select-card {
	background: white;
	border-radius: 12px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	padding: 40px;
	max-width: 600px;
	width: 100%;
}

.title {
	text-align: center;
	margin-bottom: 30px;
	font-size: 24px;
	font-weight: 600;
	color: #333;
}

.role-list {
	display: grid;
	gap: 15px;
	margin-bottom: 30px;
	max-height: 400px;
	overflow-y: auto;
}

.role-item {
	display: flex;
	align-items: center;
	padding: 15px;
	border: 2px solid #e1e5e9;
	border-radius: 8px;
	cursor: pointer;
	transition: all 0.3s ease;
}

.role-item:hover {
	border-color: #667eea;
	background-color: #f8f9ff;
}

.role-item.active {
	border-color: #667eea;
	background-color: #f0f4ff;
	box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.role-avatar {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	overflow: hidden;
	margin-right: 15px;
	border: 2px solid #e1e5e9;
}

.role-avatar img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.role-info {
	flex: 1;
}

.role-name {
	font-size: 18px;
	font-weight: 600;
	color: #333;
	margin-bottom: 5px;
}

.role-level,
.role-district {
	font-size: 14px;
	color: #666;
	margin-bottom: 2px;
}

.action-buttons {
	display: flex;
	gap: 15px;
	justify-content: center;
}

.btn {
	padding: 12px 24px;
	border: none;
	border-radius: 6px;
	font-size: 16px;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.3s ease;
	min-width: 120px;
}

.btn:disabled {
	opacity: 0.6;
	cursor: not-allowed;
}

.btn-primary {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
}

.btn-primary:hover:not(:disabled) {
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
	background: #f8f9fa;
	color: #666;
	border: 1px solid #e1e5e9;
}

.btn-secondary:hover {
	background: #e9ecef;
	transform: translateY(-1px);
}

.no-roles {
	text-align: center;
	padding: 40px 20px;
	color: #666;
}

.no-roles-icon {
	font-size: 48px;
	margin-bottom: 15px;
}

.no-roles-text {
	font-size: 18px;
	font-weight: 600;
	margin-bottom: 10px;
	color: #333;
}

.no-roles-desc {
	font-size: 14px;
	line-height: 1.5;
	color: #999;
}

/* 模态框样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
}

.modal-content {
	background: white;
	border-radius: 12px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
	max-width: 500px;
	width: 90%;
	max-height: 90vh;
	overflow-y: auto;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px 24px;
	border-bottom: 1px solid #e1e5e9;
}

.modal-header h3 {
	margin: 0;
	font-size: 20px;
	font-weight: 600;
	color: #333;
}

.close-btn {
	background: none;
	border: none;
	font-size: 24px;
	color: #999;
	cursor: pointer;
	padding: 0;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	transition: all 0.2s ease;
}

.close-btn:hover {
	background: #f5f5f5;
	color: #333;
}

.modal-body {
	padding: 24px;
}

.form-group {
	margin-bottom: 20px;
}

.form-group label {
	display: block;
	margin-bottom: 8px;
	font-size: 14px;
	font-weight: 500;
	color: #333;
}

.nickname-input-group {
	display: flex;
	gap: 8px;
	align-items: center;
}

.nickname-input {
	flex: 1;
	padding: 12px 16px;
	border: 2px solid #e1e5e9;
	border-radius: 6px;
	font-size: 16px;
	transition: border-color 0.3s ease;
}

.nickname-input:focus {
	outline: none;
	border-color: #667eea;
	box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.random-btn {
	padding: 12px;
	border: 2px solid #e1e5e9;
	border-radius: 6px;
	background: white;
	cursor: pointer;
	font-size: 16px;
	transition: all 0.3s ease;
	width: 48px;
	height: 48px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.random-btn:hover {
	border-color: #667eea;
	background: #f8f9ff;
	transform: scale(1.05);
}

.nickname-hint {
	font-size: 12px;
	color: #999;
	margin-top: 6px;
	line-height: 1.4;
}

.modal-footer {
	display: flex;
	gap: 12px;
	justify-content: flex-end;
	padding: 20px 24px;
	border-top: 1px solid #e1e5e9;
}

.modal-footer .btn {
	min-width: 100px;
}
</style>